<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\userapi\controller;

use app\common\model\UserFavorite;
use app\common\model\Goods;

/**
 * 收藏关注控制器
 */
class Favorite extends Base
{
    /**
     * 收藏/取消收藏商品
     */
    public function toggleGoodsFavorite()
    {
        $goods_id = $this->request->post('goods_id', 0);

        if (empty($goods_id)) {
            return $this->error('参数错误');
        }

        // 验证商品是否存在
        $goods = Goods::where(['id' => $goods_id, 'status' => 1])->find();
        if (empty($goods)) {
            return $this->error('商品不存在或已下架');
        }

        // 切换收藏状态
        $result = UserFavorite::toggleFavorite($this->user->id, $goods_id, 1);

        if ($result['code'] == 1) {
            return $this->success($result['msg'], ['is_favorited' => $result['is_favorited']]);
        } else {
            return $this->error($result['msg']);
        }
    }


    /**
     * 获取收藏的商品列表
     */
    public function goodsList()
    {

        $res = $this->user->favoritedGoods()->order('id desc')
            ->order('id desc')
            ->paginate($this->limit)->each(
                function ($item) {
                    $item->goods_image = $item->slider_image[0] ?? '';
                    // 商品收藏时间 而非商品添加时间
                    $item->create_time = UserFavorite::where('relation_id', $item->id)->where('type', 1)->value('create_time');
                }
            );

        $this->success('获取成功', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

}